

using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace JTC.MiniCommerce.Core.Serialization {
  
  public class Serializer {
  
    #region Methods
  
    #region Public

    /// <summary>
    /// Serializes the object.
    /// </summary>
    /// <param name="obj">The obj.</param>
    /// <param name="type">The type.</param>
    /// <returns></returns>
    public string SerializeObject(object obj, Type type) {
      string xml = string.Empty;
      XmlSerializer xs = new XmlSerializer(type);
      using(MemoryStream memoryStream = new MemoryStream()) {
        xs.Serialize(memoryStream, obj);
        memoryStream.Position = 0;
        using(StreamReader streamReader = new StreamReader(memoryStream)) {
          xml = streamReader.ReadToEnd();
        }
      }
      return xml;
    }

    /// <summary>
    /// Deserializes the object.
    /// </summary>
    /// <param name="xml">The XML.</param>
    /// <param name="typeName">Name of the type.</param>
    /// <returns></returns>
    public object DeserializeObject(string xml, string typeName) {
      object obj = null;
      XmlSerializer xs = new XmlSerializer(Type.GetType(typeName));
      StringReader stringReader = new StringReader(xml);
      obj = xs.Deserialize(stringReader);
      stringReader.Close();
      return obj;
    }
    
    #endregion
    
    #endregion

  }
}
